package com.edais.service.imp;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.ActivityDao;
import com.edais.dao.KcodeChannelDao;
import com.edais.domain.ErrorMessageSetting;
import com.edais.domain.SalesmanMonthRecord;
import com.edais.domain.SalesmanRecord;
import com.edais.domain.UserLDActivityInfo;
import com.edais.mina.TcpMinaClient;
import com.edais.service.ActivityService;
import com.edais.service.ErrorMessageService;
import com.edais.service.KcodeChannelService;
import com.edais.service.OrderService;
import com.edais.service.RateRisesCouponsService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.Message;
import com.edais.util.ThirdPartyEnvUtil;

import com.alibaba.fastjson.JSONObject;

@Service

@Transactional
public class KcodeChannelServiceImpl implements KcodeChannelService {

	private static final Log logger = LogFactory.getLog(KcodeChannelServiceImpl.class);

	@Autowired
	private KcodeChannelDao kcodeChannelDao;

	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;

	@Autowired
	private ActivityService activityService;

	@Autowired
	private ErrorMessageService errorMessageService;

	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ActivityDao activityDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public Map<String, Object> activityBidByBalanceNew(String logInfo, Map<String, Object> map) throws Exception {
		logger.info(logInfo + "锁定K码尝试激活次数表");
		int lock = activityDao.updateForLock(Long.valueOf((Integer)map.get("userId")));
		logger.info(logInfo + "锁定K码尝试激活次数表结果：" + lock);
		
		Map<String, Object> reqMap = new HashMap<String, Object>(map);
		String coopmodel = map.get("coopmodel") + "";
		if ("0".equals(coopmodel) || "-1".equals(coopmodel) || "1".equals(coopmodel) || "2".equals(coopmodel)
				|| "3".equals(coopmodel) || "4".equals(coopmodel) || "5".equals(coopmodel) || "6".equals(coopmodel)) {
			logger.info(logInfo + "赠送理财开始");
			Map<String, Object> resultMap = sendfinancial(logInfo, reqMap);
			if (resultMap != null && resultMap.size() != 0) {
				if (resultMap.containsKey("rescode")) {
					String rescode = (String) resultMap.get("rescode");
					if ("00000".equals(rescode)) {
						String vouchersType = (String) map.get("vouchersType");
						if (!StringUtils.isBlank(vouchersType)) {
							logger.info(logInfo + "赠送代金券" + vouchersType);
							Map<String, Object> parammap = new HashMap<String, Object>();
							parammap.put("vouchersType", vouchersType);
							activityService.sendVoucher(parammap, map);
						}
					}
				}
			}
			logger.info(logInfo + "赠送理财结束");
			return resultMap;
		} else {
			logger.info(logInfo + "合作模式不正确" + coopmodel);
			Map<String, Object> retMap = new HashMap<String, Object>();
			retMap.put("rescode", Consts.CHECK_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "合作模式不正确!");
			return retMap;
		}
	}

	/**
	 * K码渠道送理财
	 * 
	 * @param logInfo
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Transactional
	private Map<String, Object> sendfinancial(String logInfo, Map<String, Object> map) throws Exception {
		Map<String, Object> retMap = new HashMap<String, Object>();
		String mobile = (String) map.get("mobile");
		String buyOrderId = "";
		// 赠送理财E350008(调用核心送理财)
		logger.info(logInfo + "赠送理财理财开始");
		Map<String, Object> resMap = buyLoan(map);
		if (resMap == null || !"00000".equals(resMap.get("rescode"))) {
			logger.error(logInfo + "赠送理财异常" + resMap.get("resmsg"));
			retMap.put("rescode", Consts.CHECK_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "赠送理财异常");
			return retMap;
		}
		logger.info(logInfo + "赠送理财理财成功");
		buyOrderId = resMap.get("orderId") + "";
		map.put("buyOrderId", buyOrderId);

		logger.info(logInfo + "赠送加息券开始");
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("mobile", mobile);
		reqMap.put("userId", null);
		reqMap.put("type", "7");
		this.rateRisesCouponsService.shareKNotifyAddCoupons(reqMap);
		logger.info(logInfo + "赠送加息券结束");

		retMap.put("orderId", buyOrderId);
		retMap.put("cpType", resMap.get("cpType"));
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg", "");
		retMap.put("resmsg_cn", "");
		return retMap;
	}

	/**
	 * 活动送理财(E350008)核心入口
	 */
	public Map<String, Object> buyLoan(Map<String, Object> map) throws Exception {
		if (map == null || map.size() == 0) {
			return null;
		}

		String transCode = "E350008";

		String userId = (null == map.get("userId") ? "" : map.get("userId").toString());
		String buyAmount = (null == map.get("buyAmount") ? "" : map.get("buyAmount").toString());
		String lbAddAmount = (null == map.get("lbAddAmount") ? "" : map.get("lbAddAmount").toString());
		String kCode = map.get("kCode") == null ? "" : map.get("kCode").toString();
		String mobile = map.get("mobile") == null ? "" : map.get("mobile").toString();
		String cardNo = map.get("cardNo") == null ? "" : map.get("cardNo").toString();
		String channel = map.get("channel") == null ? "WX" : map.get("channel").toString();
		String unionMobile = map.get("unionMobile") == null ? "" : map.get("unionMobile").toString();

		// 设置报文体报文数据
		Map<String, Object> pageModel = new HashMap<String, Object>();
		pageModel.putAll(map);
		pageModel.put("userid", userId);
		pageModel.put("kCode", kCode);
		pageModel.put("cardNo", cardNo);
		pageModel.put("mobile", mobile);
		pageModel.put("amount", buyAmount);// 购买金额
		pageModel.put("lbAddAmount", lbAddAmount);// 购买金额
		pageModel.put("currency", "CNY");// 货币单位:CNY人民币，USD美元
		pageModel.put("cyclematchtype", 3);// 资金流转方式：1--收益循环投资—本息循环；2—收益每月返还—本金循环3—不循环
		pageModel.put("buyMedia", channel);// 购买媒介:1.网站；2.手机
		pageModel.put("ip", map.get("ip"));
		pageModel.put("unionMobile", unionMobile);// 联通手机号码
		Map resmap = coreUse(userId, transCode, pageModel);
		return resmap;
	}

	/**
	 * 调用核心接口
	 */
	@Transactional
	private Map coreUse(String userId, String transCode, Map<String, Object> pageModel) throws Exception {
		// 设置报文体报文数据
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModel);// 构建json字符串
		TcpMinaClient tcpMinaClient = new TcpMinaClient();
		String rtnStr = tcpMinaClient.sendMessage(jsonStr);

		if (StringUtils.isBlank(rtnStr)) {
			logger.info("调用核心接口发生异常" + ",接口id：" + transCode);
			throw new Exception("调用核心接口发生异常" + ",接口id：" + transCode);
		}

		rtnStr = rtnStr.substring(8, rtnStr.length());
		// 转化json数据为页面模型数据格式
		Map rtnMap = (HashMap) JsonUtil.getObjectFromJsonString(rtnStr, HashMap.class);

		return rtnMap;
	}

	@Override
	public Map<String, Object> selectCardNo(Map<String, Object> parmMap) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.selectCardNo(parmMap);
	}

	@Override
	public Map<String, Object> selectTimeCardNo(Map<String, Object> parmMap) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.selectTimeCardNo(parmMap);
	}

	@Async
	@Override
	public Map<String, Object> setAreaInfo(Map<String, Object> areaInfoMap) {
		// TODO Auto-generated method stub
		logger.info("#############调用设置ip归属地接口 start");
		long ipaddStartTime = new Date().getTime();
		Map<String, Object> retMap = new HashMap<String, Object>();
		String ip = null;
		String gps = "";
		if (areaInfoMap != null) {
			if (null != areaInfoMap.get("ip")) {
				ip = (String) areaInfoMap.get("ip");
			}
			if (null != areaInfoMap.get("gps")) {
				gps = (String) areaInfoMap.get("gps");
			}
		}

		if (null == ip) {
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "ip 地址为空！");
			return retMap;
		}

		try {
			// 第三方工程请求url
			String url = ThirdPartyEnvUtil.getValue("areaInfoQueryUrl");
			String requestParam = "ip=" + areaInfoMap.get("ip");
			logger.info("#############调用查询ip地址归属地接口  params:" + requestParam);
			String result = CommonUtil.sendPostByHttp(url, requestParam);// 调用查询ip地址归属地接口
			logger.info("#############调用查询ip地址归属地接口  结果：" + result);
			Map<String, Object> resultMap = new HashMap<String, Object>();
			if (!StringUtils.isBlank(result)) {
				JSONObject resultJson = JSONObject.parseObject(result);
				if (null != resultJson && !resultJson.equals("")) {
					resultMap.put("cardNo", areaInfoMap.get("cardNo"));
					resultMap.put("ip", areaInfoMap.get("ip"));
					resultMap.put("gps", gps);
					resultMap.put("provincename", resultJson.get("provincename"));
					resultMap.put("address", resultJson.get("address"));
					resultMap.put("desc", resultJson.get("desc"));
					resultMap.put("cityname", resultJson.get("cityname"));
				}
			}

			// 设置ip归属地信息
			if (null != resultMap && resultMap.size() > 0) {
				kcodeChannelDao.updateActivityAreaInfo(resultMap);
			} else {
				retMap.put("rescode", Consts.ERROR_CODE);
				retMap.put("resmsg", "");
				retMap.put("resmsg_cn", "返回为空！");
				return retMap;
			}
			retMap.put("rescode", Consts.SUCCESS_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "操作成功！");
			logger.info("#############调用设置ip归属地接口 end");
			logger.info("激活k码 ip地址解析耗费时间：" + ((new Date().getTime() - ipaddStartTime) / 1000) + "s");
			return retMap;
		} catch (Exception e) {
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			retMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			logger.error("#############调用设置ip归属地接口 网络或服务器连接异常 end");
			return retMap;
		}

	}

	@Async
	@Override
	public Map<String, Object> setAreaInfoByTd(Map<String, Object> areaInfoMap) {

		// TODO Auto-generated method stub
		String logInfo = "调用根据同盾 设置ip归属地接口 ,";
		logger.info(logInfo + "start");
		long ipaddStartTime = new Date().getTime();
		Map<String, Object> retMap = new HashMap<String, Object>();
		String ip = null;
		String gps = "";
		String token_id = "";
		String mobile="";
		if (areaInfoMap != null) {
			if (null != areaInfoMap.get("ip")) {
				ip = (String) areaInfoMap.get("ip");
			}
			if (null != areaInfoMap.get("gps")) {
				gps = (String) areaInfoMap.get("gps");
			}
			if (null != areaInfoMap.get("token_id")) {
				token_id = (String) areaInfoMap.get("token_id");
			}
			if (null != areaInfoMap.get("mobile")) {
				mobile = (String) areaInfoMap.get("mobile");
			}
		}
	
		logInfo = logInfo +"ip="+ip+ "，token_id=" + token_id;
		try {

			// 第三方工程请求url
			logger.info(logInfo + "调用查询ip地址归属地接口开始 ");
			Map<String, String> paraMap = new HashMap<String, String>();
			//paraMap.put("token_id", token_id);
			paraMap.put("flag", "5");
			paraMap.put("ip_address", ip);
			paraMap.put("account_login",mobile);  // 以下填写其他要传的参数，比如系统字段，扩展字段
			paraMap.put("account_mobile", mobile);
			//String receiveMessage = TdRequestUtil.sendTd(paraMap);
			logger.info(logInfo + "调用同盾查询ip地址归属地接口开始 ip="+ip+",tokenId="+token_id);
			String  receiveMessage= ThirdPartyEnvUtil.getThirdParty(logInfo, paraMap, "/tongdun/td");
			logger.info(logInfo + "调用同盾查询ip地址归属地接口  结果：receiveMessage=" + receiveMessage);
			
			Map<String, Object> resultMap = new HashMap<String, Object>();
			if (!StringUtils.isBlank(receiveMessage)) {
				JSONObject resultJson = JSONObject.parseObject(receiveMessage);
				if (null != resultJson && !resultJson.equals("")) {
					resultMap.put("cardNo", areaInfoMap.get("cardNo"));
					resultMap.put("ip", ip);
					resultMap.put("gps", gps);
					resultMap.put("provincename", resultJson.getString("province"));
					//resultMap.put("address",resultJson.getString("address"));
					//resultMap.put("desc", resultJson.getString("desc"));
					resultMap.put("cityname", resultJson.getString("city"));
				}
			}

			// 设置ip归属地信息
			if (null != resultMap && resultMap.size() > 0) {
				kcodeChannelDao.updateActivityAreaInfo(resultMap);
			} else {
				retMap.put("rescode", Consts.ERROR_CODE);
				retMap.put("resmsg", "");
				retMap.put("resmsg_cn", "返回为空！");
				return retMap;
			}
			retMap.put("rescode", Consts.SUCCESS_CODE);
			retMap.put("resmsg", "");
			retMap.put("resmsg_cn", "操作成功！");
			logger.info(logInfo + "调用设置ip归属地接口 end");
			logger.info(logInfo + "激活k码 ip地址解析耗费时间：" + ((new Date().getTime() - ipaddStartTime) / 1000) + "s");
			return retMap;
		} catch (Exception e) {
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			retMap.put("resmsg_cn", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			logger.error(logInfo + "调用设置ip归属地接口 网络或服务器连接异常 end");
			e.printStackTrace();
			return retMap;
		}

	}

	/**
	 * checkType 1激活校验，2手机号码校验
	 */
	@Override
	public Map<String, Object> mobileKCode(String logInfo, String mobileNumber, String checkType) throws Exception {
		String unicomSectionStr = activityService.findParamValueByName("key_code_unicom_section");
		logger.info(logInfo + "联通手机前缀key_code_unicom_section：" + unicomSectionStr);
		if (StringUtils.isBlank(unicomSectionStr)) {
			return errorMessageService.getErrorMessage("EM000000007");
		}
		String[] unicomSections = unicomSectionStr.split("\\|");
		boolean isUnicomMobile = false;
		for (String unicomSection : unicomSections) {
			if (mobileNumber.startsWith(unicomSection)) {
				isUnicomMobile = true;
				logger.info(logInfo + mobileNumber + "是联通手机号");
				break;
			}
		}
		if (isUnicomMobile) {
			logger.info(logInfo + mobileNumber + "不是联通手机号");
		}
		String errorMsgCode = "EM000000020";
		if ("2".equals(checkType)) {
			errorMsgCode = "EM000000021";
		}
		if (!isUnicomMobile) {
			return errorMessageService.getErrorMessage(errorMsgCode);
		}
		return null;
	}

	/**
	 * 设置GPS归属地
	 * 
	 * @Description: TODO
	 * @param @param
	 *            areaInfoMap
	 * @return void
	 * @throws @author
	 *             wangdanqing
	 * @date 2016-8-17
	 */
	@Async
	@Override
	public void setGpsInfo(Map<String, Object> gpsInfoMap) throws Exception {
		kcodeChannelDao.updateActivityGpsInfo(gpsInfoMap);
	}

	@Override
	public List<Map<String, Object>> queryMemberInfoList(Map<String, Object> memberMap) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.queryMemberInfoList(memberMap);
	}

	@Async
	@Override
	public void addSalesmanRecord(Map<String, Object> memberMap) throws Exception {
		// TODO Auto-generated method stub
		logger.info("===========添加销售人员返佣记录start");
		kcodeChannelDao.addSalesmanRecord(memberMap);
		logger.info("===========添加销售人员返佣记录end");
	}

	@Override
	public List<SalesmanRecord> querySaleManRecordListByDate(Map<String, Object> memberMap) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.querySaleManRecordListByDate(memberMap);
	}

	public Map<String, Object> setSalesmanMap(SalesmanRecord salesman) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != salesman) {
			resultMap.put("productModel", salesman.getProductModel());
			resultMap.put("saleCount", salesman.getSaleCount());
		}
		return resultMap;
	}

	public Map<String, Object> setSalesmanMapDetail(SalesmanRecord salesman) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != salesman) {
			resultMap.put("productModel", salesman.getProductModel());
			resultMap.put("saleCount", salesman.getSaleCount());
			resultMap.put("time", salesman.getTime());
		}
		return resultMap;
	}

	public String getShortMonth(String month) {
		String resultMonth = null;
		if (null != month) {
			if (month.length() > 1) {
				if (month.substring(0, 1).equalsIgnoreCase("0"))
					resultMonth = month.substring(1);
				else
					resultMonth = month;
			}
		}
		return resultMonth;
	}

	@Override
	public int querySaleManRecordListByDateCount(Map<String, Object> memberMap) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.querySaleManRecordListByDateCount(memberMap);
	}

	@Override
	public List<Map<String, Object>> querySetSaleManRecordList(Map<String, Object> memberMap) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<SalesmanMonthRecord> querySalesmanMonthRecord(Map<String, Object> memberMap) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.querySalesmanMonthRecord(memberMap);
	}

	@Override
	public int querySalesmanMonthRecordCount(Map<String, Object> memberMap) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.querySalesmanMonthRecordCount(memberMap);
	}

	@Override
	public Map<String, Object> preventAttacks(String logInfo, Map<String, Object> reqMap, String userId)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> historyMap = new HashMap<String, Object>();
		String mobileNumber = nullToBlank(reqMap.get("mobileNumber"));
		String kCode = nullToBlank(reqMap.get("kCode"));
		String ip = nullToBlank(reqMap.get("ip"));
		historyMap.put("userId", Long.valueOf(userId));
		historyMap.put("mobile", mobileNumber);
		historyMap.put("userIp", ip);
		historyMap.put("kCode", kCode);
		historyMap.put("isValid", "1");
		historyMap.put("activityCode", "KCODE");
		historyMap.put("activityName", "K码激活");
		logger.info(logInfo + "查询尝试激活次数");
		Map<String, Object> info = activityService.queryActivityHistoryInfoByParm(historyMap);
		if (info != null) {
			String keyCodeInfo = info.get("KEY_CODE_INFO") == null ? "" : info.get("KEY_CODE_INFO").toString();
			if (keyCodeInfo.contains(kCode)) {
				historyMap.remove("kCode");
			}
			String userIp = info.get("USER_IP") == null ? "" : info.get("USER_IP").toString();
			if (userIp.contains(ip)) {
				historyMap.remove("userIp");
			}
			historyMap.put("id", info.get("ID"));
			historyMap.put("updateTime", new Date());
			int countNumber = Integer.parseInt(info.get("COUNT_NUMBER").toString());
			int mobileUseCount = Integer.parseInt(activityService.findParamValueByName("mobile_use_key_code_count"));
			logger.info(logInfo + "已尝试激活" + countNumber + "次，可尝试次数为" + mobileUseCount);
			if (countNumber < mobileUseCount) {
				logger.info(logInfo + "通过尝试激活次数验证，更新已尝试激活次数");
				activityService.updateActivityHistoryInfoByParm(historyMap);
			} else {
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000003");
				resultMap.put("rescode", Consts.CHECK_CODE);
				resultMap.put("resmsg_cn", getErrorMsg(errorMap));
				resultMap.put("errorMap", errorMap);
				return resultMap;
			}
		} else {
			logger.info(logInfo + "新增尝试激活次数");
			activityService.addActivityHistoryInfo(historyMap);
		}
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "");
		return resultMap;
	}

	@Override
	@SuppressWarnings({ "unchecked" })
	public Map<String, Object> kcoadQualifCheck(String logInfo, Map<String, Object> reqMap, String cardNo,
			String userId) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String mobileNumber = nullToBlank(reqMap.get("mobileNumber"));// 登录手机号码
		String unionMobile = nullToBlank(reqMap.get("unionMobile")); // 联通手机号码

		Map<String, Object> channelParmMap = new HashMap<String, Object>();
		channelParmMap.put("cardNo", cardNo);
		Map<String, Object> kcodeAndChannelMap = kcodeChannelDao.selectCardNo(channelParmMap);// k码渠道信息
		logger.info(logInfo + "获取K码渠道");
		Map<String, Object> competencyMap = null;
		// K码激活资格判定，手机k码和路由器k码分开
		if (kcodeAndChannelMap != null && kcodeAndChannelMap.size() > 0) {
			String coopmodel = nullToBlank(kcodeAndChannelMap.get("COOP_MODEL"));
			// 合作模式3 验证联通手机号码
			if (coopmodel.equals("3")) {
				String checkMobile = mobileNumber;
				if (StringUtils.isNotBlank(unionMobile)) {
					checkMobile = unionMobile;
				}
				Map<String, Object> mobileKcodeMsgMap = mobileKCode(logInfo, checkMobile, "1");
				if (mobileKcodeMsgMap != null) {
					resultMap.put("rescode", Consts.CHECK_CODE);
					resultMap.put("resmsg_cn", getErrorMsg(mobileKcodeMsgMap));
					resultMap.put("errorMap", mobileKcodeMsgMap);
					return resultMap;
				}
			}
			// 合作模式4 验证IMEI
			if (coopmodel.equals("4")) {
				String imeiOne = nullToBlank(reqMap.get("imeiOne")); // 手机串号1
				String meidCheck = nullToBlank(kcodeAndChannelMap.get("MEID"));
				String imeiOneCheck = nullToBlank(kcodeAndChannelMap.get("IMEIONE"));
				String imeiTwoCheck = nullToBlank(kcodeAndChannelMap.get("IMEITWO"));
				if (!(imeiOne.equalsIgnoreCase(imeiOneCheck) || imeiOne.equalsIgnoreCase(imeiTwoCheck)
						|| imeiOne.equalsIgnoreCase(meidCheck)) || StringUtils.isBlank(imeiOne)) {
					logger.info(logInfo + "验证失败：" + imeiOne + "，meidCheck：" + meidCheck + "，" + imeiOneCheck + "，"
							+ imeiTwoCheck);
					Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000022");
					resultMap.put("rescode", Consts.CHECK_CODE);
					resultMap.put("resmsg_cn", getErrorMsg(errorMap));
					resultMap.put("errorMap", errorMap);
					return resultMap;
				}
			}
			// 合作模式3 判断联通手机号码激活次数
			if (coopmodel.equals("3")) {
				// 若未传入联通手机号码，当前登陆号码为联通号码
				if (StringUtils.isBlank(unionMobile)) {
					unionMobile = mobileNumber;
				}
				kcodeAndChannelMap.put("unionMobile", unionMobile);
			}
		} else {
			Map<String, Object> channelMap = new HashMap<String, Object>();
			channelMap.put("channelId", 1000); // 默认渠道
			kcodeAndChannelMap = kcodeChannelDao.getKeycodeChannel(channelMap); // k码渠道信息
		}
		kcodeAndChannelMap.put("userId", userId);
		kcodeAndChannelMap.put("mobile", mobileNumber);
		// K码激活次数验证
		competencyMap = commonkCodeUseCompetency(logInfo, kcodeAndChannelMap);

		if (Consts.CHECK_CODE.equals(competencyMap.get("rescode"))) {
			Map<String, Object> errorMap = new HashMap<String, Object>();
			if (competencyMap.get("errorMap") != null) {
				errorMap = (Map<String, Object>) competencyMap.get("errorMap");
				resultMap.put("resmsg_cn", getErrorMsg((Map<String, Object>) competencyMap.get("errorMap")));
			} else {
				ErrorMessageSetting errorMsgEntity = new ErrorMessageSetting();
				errorMsgEntity.setMessage_content(competencyMap.get("resmsg_cn").toString());
				errorMsgEntity.setMessage_level("1");
				errorMsgEntity.setMessage_name("KCODE_ERROR_INFO");
				errorMsgEntity.setMessage_desc("K码激活异常");
				resultMap.put("resmsg_cn", "K码激活异常");
				errorMap.put("errorMessage", errorMsgEntity);
			}
			resultMap.put("rescode", Consts.CHECK_CODE);
			resultMap.put("errorMap", errorMap);
			return resultMap;
		}
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "");
		resultMap.put("channelMap", kcodeAndChannelMap);
		return resultMap;
	}

	@Override
	public Map<String, Object> activityO2OKcode(String logInfo, Map<String, Object> reqMap) throws Exception {
		logInfo = logInfo + "激活K码系统-";
		logger.info(logInfo + "开始");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String cardNo = null;
		BigDecimal bigKcAmt = new BigDecimal("0");
		String mobileNumber = nullToBlank(reqMap.get("mobileNumber"));
		String kCode = nullToBlank(reqMap.get("kCode"));

		Map<String, Object> o2oMap = new LinkedHashMap<String, Object>();
		o2oMap.put("kCode", kCode);
		o2oMap.put("phone", mobileNumber);
		o2oMap.put("systemAp", 102);
		String param = CommonUtil.getParam(o2oMap);
		try {
			String activeKCodeUrl = activityService.findParamValueByName("lb_lingdang_kcode_use_url");
			logger.info(logInfo + "调用 url：" + activeKCodeUrl + "?" + param);
			String result = CommonUtil.doGet(activeKCodeUrl, param);
			logger.info(logInfo + "调用结果：" + result);
			if (StringUtils.isBlank(result)) {
				logger.info(logInfo + "结果为空，return");
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
				resultMap.put("rescode", Consts.CHECK_CODE);
				resultMap.put("resmsg_cn", getErrorMsg(errorMap));
				resultMap.put("errorMap", errorMap);
				return resultMap;
			}
			JSONObject jsonObj = JSONObject.parseObject(result);
			int kcodeResult = jsonObj.getIntValue("result");
			String kcodeMessage = jsonObj.getString("message");
			JSONObject data = jsonObj.getJSONObject("data");
			if (kcodeResult != 0) {
				logger.info(logInfo + "激活失败，return");
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000005");
				resultMap.put("rescode", Consts.CHECK_CODE);
				resultMap.put("resmsg_cn", kcodeMessage);
				resultMap.put("errorMap", errorMap);
				return resultMap;
			}
			cardNo = data.getString("cardNo");
			if (StringUtils.isBlank(cardNo)) {
				logger.info(logInfo + "获取卡号失败，return");
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000005");
				resultMap.put("rescode", Consts.CHECK_CODE);
				resultMap.put("resmsg_cn", getErrorMsg(errorMap));
				resultMap.put("errorMap", errorMap);
				return resultMap;
			}
			bigKcAmt = bigKcAmt.add(new BigDecimal(data.getString("money")));
		} catch (Exception e) {
			logger.error(logInfo + "异常，return", e);
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			resultMap.put("rescode", Consts.CHECK_CODE);
			resultMap.put("resmsg_cn", getErrorMsg(errorMap));
			resultMap.put("errorMap", errorMap);
			return resultMap;
		}
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "");
		resultMap.put("cardNo", cardNo);
		resultMap.put("bigKcAmt", bigKcAmt.toString());
		logger.info(logInfo + "结束");
		return resultMap;
	}

	/**
	 * 手机K码激活资格判定
	 * 
	 * @param parm
	 * @return
	 * @throws Exception
	 */
	private Map<String, Object> mobilekCodeUseCompetency(Map<String, Object> parm) throws Exception {
		logger.info("=========激活K码 手机K码激活资格判定start");
		// 合作模式
		String coopmodel = parm.get("coopmodel") + "";
		// 手机k码激活标示，1 合作模式3，2：合作模式4;3:合作模式3和合作模式4
		String mobilecodeSignCheck = "1";
		// 手机路由器的总激活台数上限（N）
		int routerTotal = 0;
		// 多次激活手机k码是否校验激活资格开关，0：默认不检查可以激活多次，1：需校验
		String mobileKcodeCheck = null;
		// 多次激活该型号手机k码所需投资金额
		BigDecimal useAmount = null;
		// 多次激活手机k码所需投资理财期数
		String remanPeriods = null;
		// 多次激活手机K码所需投资理财天数
		String remanDays = null;
		// 多次激活该手机k码所需投资理财类型
		String useType = null;
		// 开始日
		String startDate = null;
		// 结束日
		String endDate = null;
		// 激活联通手机号码
		String unionMobile = nullToBlank(parm.get("unionMobile"));
		// 若未传入联通手机号码，当前登陆号码为联通号码
		if (StringUtils.isBlank(unionMobile)) {
			unionMobile = nullToBlank(parm.get("mobile"));
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> kparamsMap = new HashMap<String, Object>();
		// Map<String, Object> unionParamMap=new HashMap<String, Object>();
		resultMap.put("remanPeriods", remanPeriods);

		// 手机k码合作模式4判断
		if (coopmodel.equalsIgnoreCase("4")) {
			mobilecodeSignCheck = "2";
			// 带串号手机路由器 总激活台数上限（N）（合作模式4）
			routerTotal = Integer.parseInt(activityService.findParamValueByName("mobile_use_model4_total_toplimit"));
			// 多次激活带串号手机k码是否校验激活资格开关，0：默认不检查可以激活多次，1：需校验（合作模式4）
			mobileKcodeCheck = activityService.findParamValueByName("mobile_k_many_model4_is_check");
			// 多次激活该型号手机k码所需投资金额（合作模式4）
			useAmount = new BigDecimal(activityService.findParamValueByName("mobile_k_model4_use_amount"));
			// 多次激活手机k码所需投资理财期数（合作模式4）
			remanPeriods = activityService.findParamValueByName("mobile_k_model4_reman_periods");
			// 多次激活手机K码所需投资理财天数（合作模式4）
			remanDays = activityService.findParamValueByName("mobile_k_model4_use_reman_days");
			// 多次激活该手机k码所需投资理财类型（合作模式4）
			useType = activityService.findParamValueByName("mobile_k_model4_use_type");
			// 开始日（合作模式4）
			startDate = activityService.findParamValueByName("mobile_k_model4_use_start_date");
			// 结束日（合作模式4）
			endDate = activityService.findParamValueByName("mobile_k_model4_use_end_date");
		} else {
			mobilecodeSignCheck = "1";
			// 带串号手机路由器 总激活台数上限（N）
			routerTotal = Integer.parseInt(activityService.findParamValueByName("mobile_router_use_total_toplimit"));
			// 多次激活手机k码是否校验激活资格开关，0：默认不检查可以激活多次，1：需校验
			mobileKcodeCheck = activityService.findParamValueByName("mobile_k_many_is_check");
			// 多次激活该型号手机k码所需投资金额
			useAmount = new BigDecimal(activityService.findParamValueByName("mobile_k_many_use_amount"));
			// 多次激活手机k码所需投资理财期数
			remanPeriods = activityService.findParamValueByName("mobile_k_many_use_reman_periods");
			// 多次激活手机K码所需投资理财天数
			remanDays = activityService.findParamValueByName("mobile_k_many_use_reman_days");
			// 多次激活该手机k码所需投资理财类型
			useType = activityService.findParamValueByName("mobile_k_many_use_type");
			// 开始日
			startDate = activityService.findParamValueByName("mobile_k_many_use_start_date");
			// 结束日
			endDate = activityService.findParamValueByName("mobile_k_many_use_end_date");
			// 判断联通手机号码是否激活过k码
			kparamsMap.put("unionMobile", unionMobile);
		}

		kparamsMap.put("mobile", parm.get("mobile"));
		kparamsMap.put("mobilekcodeSign", mobilecodeSignCheck);// 增加手机k码标志
		List<UserLDActivityInfo> activityInfoByMbList = activityService.findActivityInfoByParm(kparamsMap);

		// 订单数
		int totalNum = 0;
		// 是否激活过
		boolean isUseFlg = false;
		// 首次激活不做限制 否则判断逻辑
		if (activityInfoByMbList != null && activityInfoByMbList.size() > 0) {
			isUseFlg = true;

			if (activityInfoByMbList.size() >= routerTotal) {
				// 是否可以激活
				resultMap.put("isUseFlg", isUseFlg);
				resultMap.put("useFlg", false);
				resultMap.put("isToplimit", true);
				resultMap.put("nowUseNum", activityInfoByMbList.size());
				resultMap.put("canUseNum", 0);
				resultMap.put("totalToplimitNum", routerTotal);
				resultMap.put("needAmount", useAmount);
				resultMap.put("rescode", Consts.CHECK_CODE);

				// 提示信息修改
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000009");
				resultMap.put("resmsg_cn", getErrorMsg(errorMap));
				resultMap.put("errorMap", errorMap);
				logger.error("=========激活K码 手机K码总激活台数上限:" + getErrorMsg(errorMap));
				return resultMap;
			}
			/**
			 * 移动到核心
			 */
			// for (UserLDActivityInfo info : activityInfoByMbList) {
			// notInOrder = notInOrder + info.getStep1_order_id() + ",";
			// }
			// notInOrder = notInOrder.substring(0,notInOrder.length() -1);
			/**
			 * 移动到核心
			 */
			if ("1".equalsIgnoreCase(mobileKcodeCheck)) {
				// 获取订单列表信息
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("currentPage", 1);
				map.put("pageSize", 20);
				map.put("type", "2");
				map.put("userId", parm.get("userId"));
				map.put("startDate", startDate);
				map.put("endDate", endDate);
				map.put("minInvestAmount", useAmount);
				map.put("productType", useType);
				map.put("remanPeriods", remanPeriods);
				map.put("remanDays", remanDays);
				// map.put("notInOrder", notInOrder);
				map.put("isAddOverFlg", "1");
				map.put("mobile", parm.get("mobile"));
				// map.put("mobilekcodeSign",
				// parm.get("mobilekcodeSign"));//手机k码标志

				String result = orderService.getOrdeInfoList(map);
				JSONObject jsonObjRtn = JSONObject.parseObject(result);

				if (Consts.SUCCESS_CODE.equals(jsonObjRtn.getString("rescode"))) {
					totalNum = jsonObjRtn.getIntValue("totalNum");
					if (totalNum <= activityInfoByMbList.size() - 1) {
						resultMap.put("isUseFlg", isUseFlg);
						resultMap.put("useFlg", false);
						resultMap.put("isToplimit", false);
						resultMap.put("nowUseNum", activityInfoByMbList.size());
						resultMap.put("canUseNum", 0);
						resultMap.put("totalToplimitNum", routerTotal);
						resultMap.put("needAmount", useAmount);
						resultMap.put("rescode", Consts.CHECK_CODE);

						// 提示修改
						String[] params = { useAmount.toString(), remanDays };
						Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000008", params);
						resultMap.put("resmsg_cn", getErrorMsg(errorMap));
						resultMap.put("errorMap", errorMap);
						logger.error("=========激活K码 订单列表:" + getErrorMsg(errorMap));
						return resultMap;
					}
				} else {
					Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
					resultMap.put("rescode", Consts.CHECK_CODE);
					resultMap.put("resmsg_cn", getErrorMsg(errorMap));
					resultMap.put("errorMap", errorMap);
					logger.info("=========激活K码 订单列表 异常:" + getErrorMsg(errorMap));
					return resultMap;
				}
			}
		}

		// 是否可以激活
		resultMap.put("useFlg", true);
		// 是否已达激活上线
		resultMap.put("isToplimit", false);
		// 是否激活过
		resultMap.put("isUseFlg", isUseFlg);
		// 已激活数
		int nowUseNum = activityInfoByMbList == null ? 0 : activityInfoByMbList.size();
		resultMap.put("nowUseNum", nowUseNum);
		// 还可激活数
		int canUseNum = 0;
		if (totalNum - nowUseNum > routerTotal - nowUseNum) {
			canUseNum = routerTotal - nowUseNum;
		} else {
			canUseNum = totalNum - nowUseNum;
		}
		resultMap.put("canUseNum", canUseNum);
		// 激活上限
		resultMap.put("totalToplimitNum", routerTotal);
		// 需要投资金额
		resultMap.put("needAmount", useAmount);
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "");

		logger.info("=========激活K码 手机K码激活资格判定end");
		return resultMap;
	}

	/**
	 * K码激活资格判定
	 * 
	 * @param parm
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> kCodeUseCompetency(Map<String, Object> parm) throws Exception {
		logger.info("=========激活K码 路由器K码激活资格判定start");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> kparamsMap = new HashMap<String, Object>();
		kparamsMap.put("mobile", parm.get("mobile"));
		kparamsMap.put("mobilekcodeSign", "0");// 手机k码标志

		List<UserLDActivityInfo> activityInfoByMbList = activityService.findActivityInfoByParm(kparamsMap);
		String notInOrder = "";

		// 路由器的总激活台数上限（N）
		int routerTotal = Integer.parseInt(activityService.findParamValueByName("router_use_total_toplimit"));
		// 多次激活该型号路由器所需投资金额
		BigDecimal useAmount = new BigDecimal(activityService.findParamValueByName("k_many_use_amount"));
		// 多次激活K码所需投资理财期数
		String remanPeriods = activityService.findParamValueByName("k_many_use_reman_periods");
		// 多次激活K码所需投资理财天数
		String remanDays = activityService.findParamValueByName("k_many_use_reman_days");
		// 多次激活该型号路由器所需投资理财类型
		String useType = activityService.findParamValueByName("k_many_use_type");

		resultMap.put("remanPeriods", remanPeriods);

		// 订单数
		int totalNum = 0;
		// 是否激活过
		boolean isUseFlg = false;
		// 首次激活不做限制 否则判断逻辑
		if (activityInfoByMbList != null && activityInfoByMbList.size() > 0) {
			isUseFlg = true;

			if (activityInfoByMbList.size() >= routerTotal) {
				// 是否可以激活
				resultMap.put("isUseFlg", isUseFlg);
				resultMap.put("useFlg", false);
				resultMap.put("isToplimit", true);
				resultMap.put("nowUseNum", activityInfoByMbList.size());
				resultMap.put("canUseNum", 0);
				resultMap.put("totalToplimitNum", routerTotal);
				resultMap.put("needAmount", useAmount);
				resultMap.put("rescode", Consts.CHECK_CODE);

				// 提示信息修改
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000009");
				resultMap.put("resmsg_cn", getErrorMsg(errorMap));
				resultMap.put("errorMap", errorMap);
				logger.info("=========激活K码 路由器的总激活台数上限:" + getErrorMsg(errorMap));
				return resultMap;
			}
			/**
			 * 移动到核心
			 */
			// for (UserLDActivityInfo info : activityInfoByMbList) {
			// notInOrder = notInOrder + info.getStep1_order_id() + ",";
			// }
			// notInOrder = notInOrder.substring(0,notInOrder.length() -1);
			/**
			 * 移动到核心
			 */

			// 根据路由器型号获取参数
			// 开始日
			String startDate = activityService.findParamValueByName("k_many_use_start_date");
			// 终了
			String endDate = activityService.findParamValueByName("k_many_use_end_date");

			// 获取订单列表信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("currentPage", 1);
			map.put("pageSize", 20);
			map.put("type", "2");
			map.put("userId", parm.get("userId"));

			map.put("startDate", startDate);
			map.put("endDate", endDate);
			map.put("minInvestAmount", useAmount);
			map.put("productType", useType);
			map.put("remanPeriods", remanPeriods);
			map.put("remanDays", remanDays);
			// map.put("notInOrder", notInOrder);
			map.put("isAddOverFlg", "1");

			map.put("mobile", parm.get("mobile"));
			map.put("mobilekcodeSign", "0");

			String result = orderService.getOrdeInfoList(map);
			JSONObject jsonObjRtn = JSONObject.parseObject(result);
			if (Consts.SUCCESS_CODE.equals(jsonObjRtn.getString("rescode"))) {
				totalNum = jsonObjRtn.getIntValue("totalNum");
				if (totalNum <= activityInfoByMbList.size() - 1) {
					resultMap.put("isUseFlg", isUseFlg);
					resultMap.put("useFlg", false);
					resultMap.put("isToplimit", false);
					resultMap.put("nowUseNum", activityInfoByMbList.size());
					resultMap.put("canUseNum", 0);
					resultMap.put("totalToplimitNum", routerTotal);
					resultMap.put("needAmount", useAmount);
					resultMap.put("rescode", Consts.CHECK_CODE);

					// 提示修改
					String[] params = { useAmount.toString(), remanDays };
					Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000008", params);
					resultMap.put("resmsg_cn", getErrorMsg(errorMap));
					resultMap.put("errorMap", errorMap);
					logger.info("=========激活K码 订单列表:" + getErrorMsg(errorMap));
					return resultMap;
				}
			} else {
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
				resultMap.put("resmsg_cn", getErrorMsg(errorMap));
				resultMap.put("errorMap", errorMap);
				logger.info("=========激活K码 订单列表 异常:" + getErrorMsg(errorMap));
				return resultMap;
			}
		}

		// 是否可以激活
		resultMap.put("useFlg", true);
		// 是否已达激活上线
		resultMap.put("isToplimit", false);
		// 是否激活过
		resultMap.put("isUseFlg", isUseFlg);
		// 已激活数
		int nowUseNum = activityInfoByMbList == null ? 0 : activityInfoByMbList.size();
		resultMap.put("nowUseNum", nowUseNum);
		// 还可激活数
		int canUseNum = 0;
		if (totalNum - nowUseNum > routerTotal - nowUseNum) {
			canUseNum = routerTotal - nowUseNum;
		} else {
			canUseNum = totalNum - nowUseNum;
		}
		resultMap.put("canUseNum", canUseNum);
		// 激活上限
		resultMap.put("totalToplimitNum", routerTotal);
		// 需要投资金额
		resultMap.put("needAmount", useAmount);
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "");
		logger.info("=========激活K码 路由器K码激活资格判定end");
		return resultMap;
	}

	/**
	 * 通用 K码激活资格判定
	 * 
	 * @param parm
	 * @return
	 * @throws Exception
	 */
	private Map<String, Object> commonkCodeUseCompetency(String logInfo, Map<String, Object> parm) throws Exception {
		// 多次激活手机k码是否校验激活资格开关，0：默认不检查可以激活多次，1：需校验
		String mobileKcodeCheck = nullToBlank(parm.get("K_IS_CHECK"));

		int maxCount = Integer.valueOf(nullToBlank(parm.get("K_USE_TOTAL_TOPLIMIT"))); // 总激活台数上限
		String licaiProductType = nullToBlank(parm.get("K_USE_TYPE")); // 理财类型
		BigDecimal useAmount = new BigDecimal(nullToBlank(parm.get("K_USE_AMOUNT"))); // 理财金额
		String remanPeriods = nullToBlank(parm.get("K_USE_REMAN_PERIODS")); // 理财期数
		String remanDays = nullToBlank(parm.get("K_USE_REMAN_DAYS")); // 理财天数
		String startDate = nullToBlank(parm.get("K_USE_START_DATE")); // 理财订单开始日
		String endDate = nullToBlank(parm.get("K_USE_END_DATE")); // 理财订单结束日
		String mobilecodeSignCheck = nullToBlank(parm.get("K_TYPE"));// K码类型
		if (StringUtils.isBlank(mobilecodeSignCheck)) {
			mobilecodeSignCheck = "0";
		}
		// 激活联通手机号码
		String unionMobile = nullToBlank(parm.get("unionMobile"));

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("remanPeriods", remanPeriods); // 需要的期数 TODO
		resultMap.put("needAmount", useAmount); // 需要的金额
		resultMap.put("totalToplimitNum", maxCount); // 激活上限
		resultMap.put("useFlg", false); // 是否可以激活
		resultMap.put("isUseFlg", false); // 是否激活过
		resultMap.put("nowUseNum", 0); // 已激活数量
		resultMap.put("isToplimit", false); // 是否已达激活上限
		resultMap.put("canUseNum", 0); // 可激活数量
		resultMap.put("rescode", Consts.CHECK_CODE);
		// TODO 需要user_id
		Map<String, Object> kparamsMap = new HashMap<String, Object>();
		kparamsMap.put("mobile", parm.get("mobile"));
		kparamsMap.put("mobilekcodeSign", mobilecodeSignCheck); // K码类型
		if (!StringUtils.isBlank(unionMobile)) {
			kparamsMap.put("unionMobile", unionMobile); // K码类型
		}
		logger.info(logInfo + " 获取已激活K码数量");
		List<UserLDActivityInfo> activityInfoByMbList = activityService.findActivityInfoByParm(kparamsMap);
		int activitiedCount = activityInfoByMbList == null ? 0 : activityInfoByMbList.size();
		resultMap.put("nowUseNum", activitiedCount); // 已激活数量

		if (activitiedCount == 0) {
			logger.info(logInfo + "首次激活");
			resultMap.put("useFlg", true); // 是否可以激活
			resultMap.put("canUseNum", 1); // 可激活数量
			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg_cn", "");
			return resultMap;
		}

		resultMap.put("isUseFlg", true); // 是否激活过

		logger.info(logInfo + " 已激活K码数量：" + activitiedCount + "，激活上限：" + maxCount);
		if (activitiedCount >= maxCount) {
			logger.info(logInfo + "已达激活上线");
			resultMap.put("isToplimit", true); // 是否已达激活上限
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000009");
			resultMap.put("resmsg_cn", getErrorMsg(errorMap));
			resultMap.put("errorMap", errorMap);
			return resultMap;
		}

		if (!"1".equalsIgnoreCase(mobileKcodeCheck)) {
			logger.info(logInfo + "不检查理财订单，可激活数量：" + (maxCount - activitiedCount));
			resultMap.put("useFlg", true); // 是否可以激活
			resultMap.put("canUseNum", maxCount - activitiedCount); // 可激活数量
			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg_cn", "");
			return resultMap;
		}

		int licaiOrderCount = 0; // 需要购买的理财已购买数量
		// 获取理财订单列表
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("currentPage", 1);
		map.put("pageSize", 1);
		map.put("type", "2"); // 1处理中 2还款中 3已完成 4投资失败
		map.put("userId", parm.get("userId"));
		map.put("mobile", parm.get("mobile"));
		map.put("startDate", startDate);
		map.put("endDate", endDate);
		map.put("minInvestAmount", useAmount);
		map.put("productType", licaiProductType);
		map.put("remanPeriods", remanPeriods);
		map.put("remanDays", remanDays);
		map.put("isAddOverFlg", "1"); // 是否添加已完成订单 3已完成
		logger.info(logInfo + "获取理财订单");
		String result = orderService.getOrdeInfoList(map);
		JSONObject jsonObjRtn = JSONObject.parseObject(result);
		if (Consts.SUCCESS_CODE.equals(jsonObjRtn.getString("rescode"))) {
			licaiOrderCount = jsonObjRtn.getIntValue("totalNum");
			logger.info(logInfo + "理财订单数量：" + licaiOrderCount + "，已激活订单数量：" + activitiedCount);
			// 您还需要单笔投资{0}元的锁定期至少为{1}天的定期理财产品才能激活该K码
			if (licaiOrderCount < activitiedCount) {
				logger.info(logInfo + "理财订单数量小于已激活订单数量");
				resultMap.put("rescode", Consts.CHECK_CODE);
				String[] params = { useAmount.toString(), remanDays }; // TODO
				Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000008", params);
				resultMap.put("resmsg_cn", getErrorMsg(errorMap));
				resultMap.put("errorMap", errorMap);
				return resultMap;
			}
		} else {
			logger.error(logInfo + "获取理财订单列表异常");
			Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000007");
			resultMap.put("rescode", Consts.CHECK_CODE);
			resultMap.put("resmsg_cn", getErrorMsg(errorMap));
			resultMap.put("errorMap", errorMap);
			return resultMap;
		}

		resultMap.put("useFlg", true); // 是否可以激活
		// 可激活数量
		resultMap.put("canUseNum",
				licaiOrderCount < maxCount ? licaiOrderCount - activitiedCount : maxCount - activitiedCount);
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "");
		return resultMap;
	}

	private String nullToBlank(Object obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString();
	}

	private String getErrorMsg(Map<String, Object> errorMap) {
		// TODO Auto-generated method stub
		ErrorMessageSetting emsEntity = (ErrorMessageSetting) errorMap.get("errorMessage");
		String emsStr = "";
		if (null != emsEntity) {
			emsStr = emsEntity.getMessage_content();
		}
		return emsStr;
	}

	public static void main(String[] args) {
		KcodeChannelServiceImpl aa = new KcodeChannelServiceImpl();
		Map<String, Object> areaInfoMap = new HashMap<String, Object>();
		areaInfoMap.put("token_id", "e0457sldhvnd5mmcn6h0kmxb8c63z4");
		areaInfoMap.put("cardNo", "aZGFM3RRUr");
		areaInfoMap.put("ip", "180.167.29.170");
		try {
			aa.setAreaInfoByTd(areaInfoMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public int selectIllegal(Map<String, Object> params) throws Exception {
		// TODO Auto-generated method stub
		return kcodeChannelDao.selectIllegal(params);
	}
	
	/** 
	 * 方法名称:transStringToMap 
	 * 传入参数:mapString 形如 username'chenziwen^password'1234 
	 * 返回值:Map 
	*/  
	public static Map transStringToMap(String mapString){  
	  Map map = new HashMap();  
	  java.util.StringTokenizer items;  
	  for(StringTokenizer entrys = new StringTokenizer(mapString, "^");entrys.hasMoreTokens();   
	    map.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))  
	      items = new StringTokenizer(entrys.nextToken(), "'");  
	  return map;  
	}

	@Override
	public String importKcodeInfo(String loggerInfo,JSONObject jsonParam) {
		logger.info(loggerInfo+" k码数据导入开始");
		//取出参数
		String cardNo=jsonParam.getString("cardNo").trim();
		String channelId=jsonParam.getString("channelId").trim();
		String channelName=jsonParam.getString("channelName").trim();
		String snNo=jsonParam.getString("snNo");
		String imeione=jsonParam.getString("imeione");
		String imeitwo=jsonParam.getString("imeitwo");
		String meid=jsonParam.getString("meid");
		String createPer="网点输入";
		//1.查询卡号是否存在
		if(kcodeChannelDao.queryKeyCodeCountByCardNo(cardNo)>0){
			logger.info(loggerInfo+" 卡号已存在");
			return "卡号已存在！";
		}
		//2.查询渠道是否存在
		Map<String, Object> channelMap=new HashMap<String,Object>();
		channelMap.put("channelId", Long.valueOf(channelId));
		channelMap.put("buyChannel", channelName);
		if(kcodeChannelDao.queryChannelCountByParam(channelMap)<1){
			logger.info(loggerInfo+" 渠道不存在");
			return "渠道不存在！";
		}
		//3.添加k码信息
		Map<String, Object> kcodeMap=new HashMap<String,Object>();
		kcodeMap.put("cardNo", cardNo);
		kcodeMap.put("channelId", Long.valueOf(channelId.trim()));
		kcodeMap.put("snNo", snNo);
		kcodeMap.put("imeione", imeione);
		kcodeMap.put("imeitwo", imeitwo);
		kcodeMap.put("meid", meid);
		kcodeMap.put("createPer", createPer);
		
		if(kcodeChannelDao.insertKeycodeInfo(kcodeMap)<1){
			logger.info(loggerInfo+" k码数据导入失败");
			return "k码数据导入失败！";
		}
		//4.删除非法k码表信息
		kcodeChannelDao.updateKcodeIllegalByCardNo(cardNo);
		logger.info(loggerInfo+" k码数据导入结束");
		return null;
	}  
}
